package com.hamilton.erik.pt.core.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.hamilton.erik.pt.core.dao.UserDAO;
import com.hamilton.erik.pt.core.db.H2JdbcAccess;
import com.hamilton.erik.pt.core.model.User;

public class H2UserDAO implements UserDAO {

	private final String USER_DB_TABLE = "APPLICATION.USER_ACCOUNT";
	
	private final String INSERT_USER = 
			String.format(
				"INSERT INTO %s (USER_NAME, HASH, SALT) " +
				"VALUES (?, ?, ?)",
				USER_DB_TABLE);
	
	private final String SELECT_USER = 
			String.format(
				"SELECT * FROM %s WHERE USER_NAME = ?",
				USER_DB_TABLE);
	
	@Override
	public int insertUser(User user) throws SQLException {
		
		Connection conn = null;
		
		try {
			conn = H2JdbcAccess.getInstance().getConnection();
						
			PreparedStatement stmt = conn.prepareStatement(INSERT_USER);
		
			stmt.setString(1, user.getUserName());
			stmt.setString(2, user.getHash());
			stmt.setString(3, user.getSalt());
			
			return stmt.executeUpdate();
			
		} catch (SQLException e) {
			throw e;
		} finally {
			if(conn != null) try { conn.close(); } catch (Exception ignore) {}
		}
	}

	@Override
	public boolean deleteUser(User user) throws SQLException  {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public User findUser(String userName) throws SQLException {
		
		User user = null;
		Connection conn = null;
		
		try {
			conn = H2JdbcAccess.getInstance().getConnection();
						
			PreparedStatement stmt = conn.prepareStatement(SELECT_USER);
		
			stmt.setString(1, userName);
			
			ResultSet rs = stmt.executeQuery();
			
			if(rs.next()) {
				user = new User();

				user.setUserName(rs.getString(1));
				user.setHash(rs.getString(2));
				user.setSalt(rs.getString(3));
			}

			return user;
		} catch (SQLException e) {
			throw e;
		} finally {
			if(conn != null) try { conn.close(); } catch (Exception ignore) {}
		}
	}

	@Override
	public int updateUser(User user) throws SQLException  {
		// TODO Auto-generated method stub
		return -1;
	}

	@Override
	public boolean userExists(String userName) throws SQLException {
		return (findUser(userName) != null);
	}
}
